package com.example.mynetwork2.recyclerview.netrequest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mynetwork2.R;
import com.example.mynetwork2.recyclerview.MyAdapter;
import com.example.mynetwork2.recyclerview.NewsBean;
import com.example.mynetwork2.recyclerview.SimpleDividerDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RecyclerVNetRequestActivity extends AppCompatActivity {
    private List<NewsBean> newsList;
    RecyclerView myRecyclerView;
    MyAdapter myAdapter;
    SwipeRefreshLayout refreshLayout;
    //创建handler
    private  Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 100:
                    List<NewsBean> datas = (List<NewsBean>) msg.obj;
                    if (datas!=null){
                        //停止刷新转圈效果
                        refreshLayout.setRefreshing(false);
                    }
                    newsList=datas;
                    myAdapter.setDatas(newsList);
                    myAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview_net);
        myRecyclerView= findViewById(R.id.my_recyclerview);
        //刷新控件
        refreshLayout=  findViewById(R.id.my_refresh);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {//下拉刷新的触发方法
                //刷新获取最新的数据
                getNetData();
            }
        });

        initData();
        getNetData();
    }



    private void initData() {
        newsList= new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        myRecyclerView.setLayoutManager(linearLayoutManager);
        myRecyclerView.addItemDecoration(new SimpleDividerDecoration(this));
        myAdapter = new MyAdapter(this, newsList);
        myRecyclerView.setAdapter(myAdapter);


    }
    //获取网络数据
    private void getNetData() {
        OkHttpClient client = new OkHttpClient();
        String url ="http://10.111.34.9:8080/okhttp/getnewlist";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //异常的时候就停止刷新
                refreshLayout.setRefreshing(false);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String jsonData = response.body().string();
                Gson gson = new Gson();
                ResponseBean responseBean = gson.fromJson(jsonData, ResponseBean.class);
                List<NewsBean> datas = responseBean.getDatas();
//                //第一种方式直接赋值给适配器
//                newsList = datas;
//                //获取到的最新数据传给适配器
//                myAdapter.setDatas(newsList);
//                //因为此时在子线程，这里涉及到主线程的UI更新，所以需要在主线程里面去更新调用notifyDataSetChanged
//                RecyclerVNetRequestActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
                            //刷新适配器
//                        myAdapter.notifyDataSetChanged();
//                    }
//                });
                //第二种方式：Handler 线程通信： 由子线程传到主线程
                Message msg = Message.obtain();
                msg.what=100;
                msg.obj=datas;
                handler.sendMessage(msg);

            }
        });


    }

}
